import React, {Component} from 'react';
import {Input, Table, Button, message} from 'antd';
import "./UpperPartOfTheForm.css"

class UpperPartOfTheForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            Time: [],//第一列的时间变化自动控制
            Data: [],//原始填写的数据
            // [null,null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null],
            // [null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null],
            // [null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null],
            // [null,null,null,null,null,null,null,null],[null,null,null,null,null,null,null,null],
            // [null,null,null,null,null,null,null,null]
            average: [null, null, null, null, null, null, null, null, null,
                null, null, null, null, null, null, null, null, null,
                null, null, null, null, null, null, null, null, null],//平均
            ratio: [null, null, null, null, null, null, null, null, null,
                null, null, null, null, null, null, null, null, null,
                null, null, null, null, null, null, null, null, null,],//比值
            passRate: [null, null, null, null, null, null, null, null, null,
                null, null, null, null, null, null, null, null, null,
                null, null, null, null, null, null, null, null, null,],//合格率
            isNormal: [],
            // person: this.props.person
        }
    }

    /**
     * 第一列的时间变化
     */
    /**初始化**/
    componentDidMount() {
        //绑定ref
        this.props.onRef(this);
    }

    componentWillMount() {
        const allTime = [
            ['00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00'],
            ['08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00'],
            ['16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00']
        ];
        this.setState({
            Time: [...allTime[this.props.timeChose]],
            Data: this.props.upperData,
            timeChose: this.props.timeChose,
        });
    }

    /**更新props**/
    componentWillReceiveProps(nextProps) {
        const allTime = [
            ['00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00'],
            ['08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00'],
            ['16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00']
        ];
        this.setState({
            Time: [...allTime[nextProps.timeChose]],
            Data: nextProps.upperData,
            timeChose: nextProps.timeChose,
        });
        this.updataData_Initial(nextProps.standard);
    }


    updataData_Initial(standard) {
        let temp1 = 0;//计算均值和合格率的临时数据
        let temp2 = 0;
        let temp3 = 0;
        let str = '';//计算合格比率的临时数据
        let inputCount0 = [], inputCount8 = [], inputCount16 = [];//各班次输入的总数
        let passCount0 = [], passCount8 = [], passCount16 = [];//各班次的合格数
        let passRate0 = [], passRate8 = [], passRate16 = [];//各班次的合格率
        let ratio0 = [], ratio8 = [], ratio16 = [];//各班次的合格比率
        //计算合格率部分
        for (let i = 0; i < 9; i++) {//i是列
            inputCount0[i] = 0;//0点班输入的总数
            passCount0[i] = 0;//0点班合格数
            inputCount8[i] = 0;//8点班输入的总数
            passCount8[i] = 0;//8点班合格数
            inputCount16[i] = 0;//16点班输入的总数
            passCount16[i] = 0;//16点班合格数
            for (let j = 0; j <= 7; j++) {//j是行
                if (!isNaN(this.state.Data[j]['shuju'][i]) && (this.state.Data[j]['shuju'][i] != null)) {
                    inputCount0[i]++;
                    if (this.state.Data[j]['shuju'][i] <= standard[i]) {
                        passCount0[i]++;
                    }
                }
                if (inputCount0[i] === 0) {
                    str = null;
                    temp1 = null;
                }
                else {
                    str = passCount0[i] + '\/' + inputCount0[i];
                    if (isNaN(temp1 = passCount0[i] / inputCount0[i])) {
                        temp1 = null;
                    }
                    else {
                        temp1 = Number(temp1 * 100).toFixed(1) + '%';
                    }
                }
                ratio0[i] = str;
                passRate0[i] = temp1;
            }
            for (let j = 8; j <= 15; j++) {//j是行
                if (!isNaN(this.state.Data[j]['shuju'][i]) && (this.state.Data[j]['shuju'][i] != null)) {
                    inputCount8[i]++;
                    if (this.state.Data[j]['shuju'][i] <= standard[i]) {
                        passCount8[i]++;
                    }
                }
                if (inputCount8[i] === 0) {
                    str = null;
                    temp1 = null;
                }
                else {
                    str = passCount8[i] + '\/' + inputCount8[i];
                    if (isNaN(temp1 = passCount8[i] / inputCount8[i])) {
                        temp1 = null;
                    }
                    else {
                        temp1 = Number(temp1 * 100).toFixed(1) + '%';
                    }
                }
                ratio8[i] = str;
                passRate8[i] = temp1;
            }
            for (let j = 16; j <= 23; j++) {//j是行
                if (!isNaN(this.state.Data[j]['shuju'][i]) && (this.state.Data[j]['shuju'][i] != null)) {
                    inputCount16[i]++;
                    if (this.state.Data[j]['shuju'][i] <= standard[i]) {
                        passCount16[i]++;
                    }
                }
                if (inputCount16[i] === 0) {
                    str = null;
                    temp1 = null;
                }
                else {
                    str = passCount16[i] + '\/' + inputCount16[i];
                    if (isNaN(temp1 = passCount16[i] / inputCount16[i])) {
                        temp1 = null;
                    }
                    else {
                        temp1 = Number(temp1 * 100).toFixed(1) + '%';
                    }
                }
                ratio16[i] = str;
                passRate16[i] = temp1;
            }
            let ratio = ratio0.concat(ratio8);
            ratio = ratio.concat(ratio16);
            let passRate = passRate0.concat(passRate8);
            passRate = passRate.concat(passRate16);
            this.setState({
                ratio: ratio,
                passRate: passRate,
            })
        }
        //计算均值的部分
        let average0 = [], average8 = [], average16 = [];//各班次的合格率
        for (let i = 0; i < 9; i++) {
            temp1 = 0;
            temp2 = 0;
            temp3 = 0;
            if (inputCount0[i] === 0) {
                temp1 = null;
            }
            else {
                for (let j = 0; j < 8; j++) {
                    if (!isNaN(this.state.Data[j]['shuju'][i])) {
                        temp1 += this.state.Data[j]['shuju'][i];
                    }
                }
                if (isNaN(temp1 = temp1 / inputCount0[i])) {
                    temp1 = 0;
                }
                temp1 = temp1.toFixed(3);
            }
            average0[i] = temp1;
            if (inputCount8[i] === 0) {
                temp2 = null;
            }
            else {
                for (let j = 8; j < 16; j++) {
                    if (!isNaN(this.state.Data[j]['shuju'][i])) {
                        temp2 += this.state.Data[j]['shuju'][i];
                    }
                }
                if (isNaN(temp2 = temp2 / inputCount8[i])) {
                    temp2 = 0;
                }
                temp2 = temp2.toFixed(3);
            }
            average8[i] = temp2;
            if (inputCount16[i] === 0) {
                temp3 = null;
            }
            else {
                for (let j = 16; j < 24; j++) {
                    if (!isNaN(this.state.Data[j]['shuju'][i])) {
                        temp3 += this.state.Data[j]['shuju'][i];
                    }
                }
                if (isNaN(temp3 = temp3 / inputCount16[i])) {
                    temp3 = 0;
                }
                temp3 = temp3.toFixed(3);
            }
            average16[i] = temp3;
        }
        let average = average0.concat(average8);
        average = average.concat(average16);
        this.setState({
            average: average
        });
        //是否正常的更新部分
        let newNormal = [];
        for (let i = 0; i < 24; i++) {
            if (!isNaN(this.state.Data[i]['shuju'][0]) && (this.state.Data[i]['shuju'][0] != null)) {
                if (this.state.Data[i]['shuju'][0] <= standard[0]) {
                    newNormal[i] = '正常';
                }
                else {
                    newNormal[i] = '异常';
                }
            }
            else {
                newNormal[i] = '';
            }
        }
        this.setState({
            isNormal: newNormal
        })
    }

    /***
     * 进行底部的合格率、平均数的计算更新以及是否正常的判断
     **/
    updataData(standard) {
        let temp1 = 0;
        let inputCount = [];
        let passCount = [];
        let str = '';
        let xiaoshi = this.props.timeChose * 8;//都加上选择的时间
        const Data = this.state.Data;
        const ratio = this.state.ratio;
        const passRate = this.state.passRate;
        const average = this.state.average;
        for (let i = 0; i < 9; i++) {//i是列
            inputCount[i] = 0;//输入的总数
            passCount[i] = 0;//合格数
            for (let j = xiaoshi; j < xiaoshi + 8; j++) {//j是行
                // Data[j]['shuju'][i] = parseFloat(Data[j]['shuju'][i]);
                if (!isNaN(parseFloat(Data[j]['shuju'][i])) && (parseFloat(Data[j]['shuju'][i]) != null)) {
                    inputCount[i]++;
                    if (parseFloat(Data[j]['shuju'][i]) <= standard[i]) {
                        passCount[i]++;
                    }
                }
                if (inputCount[i] === 0) {
                    str = null;
                    temp1 = null;
                }
                else {
                    str = passCount[i] + '\/' + inputCount[i];
                    if (isNaN(temp1 = passCount[i] / inputCount[i])) {
                        temp1 = null;
                    }
                    else {
                        temp1 = Number(temp1 * 100).toFixed(1) + '%';
                    }
                }
                ratio[i + this.state.timeChose * 9] = str;
                // console.log(ratio)
                passRate[i + this.state.timeChose * 9] = temp1;
            }
        }
        //计算均值的部分
        for (let i = 0; i < 9; i++) {
            temp1 = 0;
            if (inputCount[i] === 0) {
                temp1 = null;
            }
            else {
                for (let j = xiaoshi; j < xiaoshi + 8; j++) {
                    if (!isNaN(parseFloat(Data[j]['shuju'][i]))) {
                        temp1 += parseFloat(Data[j]['shuju'][i]);
                    }
                }
                if (isNaN(temp1 = temp1 / inputCount[i])) {
                    temp1 = 0;
                }
                temp1 = temp1.toFixed(3);
            }
            average[i + this.props.timeChose * 9] = temp1;
        }
        this.setState({
            ratio: ratio,//比值
            passRate: passRate,//合格率
            average: average
        });
        //是否正常的更新部分
        for (let i = xiaoshi; i < xiaoshi + 8; i++) {
            const newNormal = this.state.isNormal;
            if (!isNaN(Data[i]['shuju'][0]) && (Data[i]['shuju'][0] != null)) {
                if (Data[i]['shuju'][0] <= standard[0]) {
                    newNormal[i] = '正常';
                }
                else {
                    newNormal[i] = '异常';
                }
            }
            else {
                newNormal[i] = '';
            }
            this.setState({
                isNormal: newNormal
            })
        }
    }


    /**
     * 表格输入数据变化的监听
     **/
    onInputNumberChange2 = (event, indexH, indexL) => {
        let NewData = this.state.Data;
        let xiaoshi = indexH + this.props.timeChose * 8;
        const rep = /^(\-)*(\d+)\.(\d{2}).*$/;
        event = event.replace(rep, '$1$2.$3');
        NewData[xiaoshi]["shuju"][indexL] = event;
        this.setState({
            Data: NewData
        });
    };
    onInputNumberChange3 = (event, indexH, indexL) => {
        let NewData = this.state.Data;
        let xiaoshi = indexH + this.props.timeChose * 8;
        const rep = /^(\-)*(\d+)\.(\d{3}).*$/;
        event = event.replace(rep, '$1$2.$3');
        NewData[xiaoshi]["shuju"][indexL] = event;
        this.setState({
            Data: NewData
        });
    };
    //控制输入框的样式
    changeStyle = (value) => {
        if (value) {
            if (isNaN(value) || value > 100) {
                return {
                    borderColor: 'red',
                    color: 'red',
                }
            }
        }
    }

    //上传当前数据后台
    /**点击暂存之后上传当前行的数据到后台**start**/
    postToHome(i) {//i是行数
        const xiaoshi = i + this.props.timeChose * 8;
        const a = this.state.Data[xiaoshi]['shuju'];
        const shuju = a.join(',');
        const jsondata = {
            "data": [
                {
                    "riqi": this.props.riqi,
                    "xiaoshi": xiaoshi,
                    "leixing": "KZS",
                    "zhonglei": 1,
                    "shuju": shuju,
                    "name": window.localStorage.name,
                }
            ]
        };
        fetch("/api/HuaYS/save", {
            method: 'POST',
            body: JSON.stringify(jsondata), // data can be `string` or {object}!
            headers: {
                'Content-Type': 'application/json',
                'authorization': window.localStorage.authorization,
            }
        })
            .then(res => res.json())
            .then(data => {
                if (data['code'] === 0) {
                    message.info('暂存成功');
                    const Data = this.state.Data;
                    Data[xiaoshi]['name'] = window.localStorage.name;
                    this.setState({
                        Data: Data
                    })
                }
            })
            .catch(error => console.error('Error:', error))
            .then(response => console.log('Success:', response));
    }

    /**点击暂存之后上传当前行的数据到后台**end**/


    render() {
        /**表头的设计**start**/
        const columns = [
            {
                title: '时间',
                width: "10%",
                key: 'time',
                dataIndex: 'time',
            },
            {
                title: '熟料',
                dataIndex: 'ShuL',
                key: 'ShuL',
                children: [{
                    title: 'FCaO/%',
                    width: "7.5%",
                    key: 'FCaO',
                    dataIndex: 'FCaO',
                    render: (value, row, index) => {
                        const obj = {
                            children: value,
                            props: {}
                        };
                        if (index === 9) {
                            obj.props.colSpan = 2;
                        }
                        if (index === 10) {
                            obj.props.colSpan = 2;
                        }
                        if (index === 11) {
                            obj.props.colSpan = 2;
                        }
                        return obj;
                    },
                }, {
                    title: '是否正常',
                    width: "7.5%",
                    key: 'IsNormal',
                    dataIndex: 'IsNormal',
                    render: (value, row, index) => {
                        const obj = {
                            children: value,
                            props: {}
                        };
                        if (index === 9) {
                            obj.props.colSpan = 0
                        }
                        if (index === 10) {
                            obj.props.colSpan = 0;
                        }
                        if (index === 11) {
                            obj.props.colSpan = 0;
                        }
                        return obj;
                    },
                }
                ],

            },
            {
                title: '出磨生料',
                key: 'Chu',
                children: [
                    {
                        title: '细度/um',
                        width: "7.5%",
                        key: 'ChuFineness',
                        dataIndex: 'ChuFineness'
                    },
                    {
                        title: '900孔',
                        width: "7.5%",
                        key: 'Chu900',
                        dataIndex: 'Chu900'
                    },
                    {
                        title: '水分',
                        width: "7.5%",
                        key: 'ChuWater',
                        dataIndex: 'ChuWater'
                    }
                ],
            },
            {
                title: '入磨生料',
                key: 'Ru',
                children: [
                    {
                        title: '细度/um',
                        width: "7.5%",
                        key: 'RuFineness',
                        dataIndex: 'RuFineness'
                    },
                    {
                        title: '900孔',
                        width: "7.5%",
                        key: 'Ru900',
                        dataIndex: 'Ru900'
                    },
                    {
                        title: '水分',
                        width: "7.5%",
                        key: 'RuWater',
                        dataIndex: 'RuWater'
                    }
                ],
            },
            {
                title: '煤粉',
                key: 'Coal',
                children: [
                    {
                        title: '细度/um',
                        width: "7.5%",
                        key: 'CoalFineness',
                        dataIndex: 'CoalFineness'
                    },
                    {
                        title: '水分',
                        width: "7.5%",
                        key: 'CoalWater',
                        dataIndex: 'CoalWater'
                    }
                ],
            },
            {
                title: '人员',
                width: "7.5%",
                key: 'person',
                dataIndex: 'person',
                render: (value, row, index) => {
                    const obj = {
                        children: value,
                        props: {}
                    };
                    if (index === 9) {
                        obj.props.rowSpan = 3;
                    }
                    if (index === 10) {
                        obj.props.rowSpan = 0;
                    }
                    if (index === 11) {
                        obj.props.rowSpan = 0;
                    }

                    return obj;
                },
            },
            {
                title: '暂存',
                width: "7.5%",
                key: 'btn_save',
                dataIndex: 'btn_save',
                render: (value, row, index) => {
                    const obj = {
                        children: value,
                        props: {}
                    };
                    if (index === 9) {
                        obj.props.rowSpan = 3;
                    }
                    if (index === 10) {
                        obj.props.rowSpan = 0;
                    }
                    if (index === 11) {
                        obj.props.rowSpan = 0;
                    }

                    return obj;
                },
            }
        ];
        /**表头的设计**end**/

        /**第一行里的标准**start**/
        const data = [
            {
                time: '指标',
                FCaO: '≤' + this.props.standard[0],
                ChuFineness: '≤' + this.props.standard[1],
                Chu900: '≤' + this.props.standard[2],
                ChuWater: '≤' + this.props.standard[3],
                RuFineness: '≤' + this.props.standard[4],
                Ru900: '≤' + this.props.standard[5],
                RuWater: '≤' + this.props.standard[6],
                CoalFineness: '≤' + this.props.standard[7],
                CoalWater: '≤' + this.props.standard[8]
            }

        ];
        /**第一行里的标准**end**/

        /**限制输入数值位数的函数**start**/
        const limitDecimals = (value: string | number): string => {
            const reg = /^(\-)*(\d+)\.(\d\d).*$/;
            if (typeof value === 'string') {
                return !isNaN(Number(value)) ? value.replace(reg, '$1$2.$3') : ''
            } else if (typeof value === 'number') {
                return !isNaN(value) ? String(value).replace(reg, '$1$2.$3') : ''
            } else {
                return ''
            }
        };
        /**限制输入数值位数的函数**end**/

        /**中间八行的数据输入**start**/
        const Data = this.state.Data;
        for (let i = 0; i < 8; i++) {
            const xiaoshi = this.props.timeChose * 8;
            const value = Data[i + xiaoshi]['shuju'];
            data.push(
                {
                    time: this.state.Time[i],
                    FCaO: <span><Input
                        style={this.changeStyle(value[0])}
                        defaultValue={''}
                        value={isNaN(value[0]) ? null : value[0]}
                        onBlur={() => this.updataData(this.props.standard)}
                        onChange={event => this.onInputNumberChange2(event.target.value, i, 0)}
                    /></span>,
                    IsNormal:
                        this.state.isNormal[i + xiaoshi],
                    ChuFineness: <span><Input
                        style={this.changeStyle(value[1])}
                        defaultValue={''}
                        value={isNaN(value[1]) ? null : value[1]}
                        onBlur={() => this.updataData(this.props.standard)}
                        onChange={event => this.onInputNumberChange2(event.target.value, i, 1)}
                    /></span>,
                    Chu900: <span><Input
                        style={this.changeStyle(value[2])}
                        defaultValue={''}
                        value={isNaN(value[2]) ? null : value[2]}
                        onBlur={() => this.updataData(this.props.standard)}
                        onChange={event => this.onInputNumberChange2(event.target.value, i, 2)}
                    /></span>,
                    ChuWater: <span><Input
                        style={this.changeStyle(value[3])}
                        defaultValue={''}
                        value={isNaN(value[3]) ? null : value[3]}
                        onBlur={() => this.updataData(this.props.standard)}
                        onChange={event => this.onInputNumberChange2(event.target.value, i, 3)}
                    /></span>,
                    RuFineness: <span><Input
                        style={this.changeStyle(value[4])}
                        defaultValue={''}
                        value={isNaN(value[4]) ? null : value[4]}
                        onBlur={() => this.updataData(this.props.standard)}
                        onChange={event => this.onInputNumberChange2(event.target.value, i, 4)}
                    /></span>,
                    Ru900: <span><Input
                        style={this.changeStyle(value[5])}
                        defaultValue={''}
                        value={isNaN(value[5]) ? null : value[5]}
                        onBlur={() => this.updataData(this.props.standard)}
                        onChange={event => this.onInputNumberChange2(event.target.value, i, 5)}
                    /></span>,
                    RuWater: <span><Input
                        style={this.changeStyle(value[6])}
                        defaultValue={''}
                        value={isNaN(value[6]) ? null : value[6]}
                        onBlur={() => this.updataData(this.props.standard)}
                        onChange={event => this.onInputNumberChange2(event.target.value, i, 6)}
                    /></span>,
                    CoalFineness: <span><Input
                        style={this.changeStyle(value[7])}
                        defaultValue={''}
                        value={isNaN(value[7]) ? null : value[7]}
                        onBlur={() => this.updataData(this.props.standard)}
                        onChange={event => this.onInputNumberChange2(event.target.value, i, 7)}
                    /></span>,
                    CoalWater: <span><Input
                        style={this.changeStyle(value[8])}
                        defaultValue={''}
                        value={isNaN(value[8]) ? null : value[8]}
                        onBlur={() => this.updataData(this.props.standard)}
                        onChange={event => this.onInputNumberChange2(event.target.value, i, 8)}
                    /></span>,
                    person: Data[i + xiaoshi]['name'],
                    btn_save: <Button type='primary' onClick={() => this.postToHome(i)}>暂存</Button>,
                }
            )
        }
        /**中间八行的数据输入**end**/

        /**数据的自动处理显示部分**start**/
        const xiaoshi = this.props.timeChose * 9;
        data.push(
            {
                time: '平均',
                FCaO: this.state.average[0 + xiaoshi],
                ChuFineness: this.state.average[1 + xiaoshi],
                Chu900: this.state.average[2 + xiaoshi],
                ChuWater: this.state.average[3 + xiaoshi],
                RuFineness: this.state.average[4 + xiaoshi],
                Ru900: this.state.average[5 + xiaoshi],
                RuWater: this.state.average[6 + xiaoshi],
                CoalFineness: this.state.average[7 + xiaoshi],
                CoalWater: this.state.average[8 + xiaoshi]

            }, {
                time: '总合格数\/总数',
                FCaO: this.state.ratio[0 + xiaoshi],
                ChuFineness: this.state.ratio[1 + xiaoshi],
                Chu900: this.state.ratio[2 + xiaoshi],
                ChuWater: this.state.ratio[3 + xiaoshi],
                RuFineness: this.state.ratio[4 + xiaoshi],
                Ru900: this.state.ratio[5 + xiaoshi],
                RuWater: this.state.ratio[6 + xiaoshi],
                CoalFineness: this.state.ratio[7 + xiaoshi],
                CoalWater: this.state.ratio[8 + xiaoshi]

            }, {
                time: '合格率',
                FCaO: this.state.passRate[0 + xiaoshi],
                ChuFineness: this.state.passRate[1 + xiaoshi],
                Chu900: this.state.passRate[2 + xiaoshi],
                ChuWater: this.state.passRate[3 + xiaoshi],
                RuFineness: this.state.passRate[4 + xiaoshi],
                Ru900: this.state.passRate[5 + xiaoshi],
                RuWater: this.state.passRate[6 + xiaoshi],
                CoalFineness: this.state.passRate[7 + xiaoshi],
                CoalWater: this.state.passRate[8 + xiaoshi]
            }
        );
        /**数据的自动处理显示部分**end**/


        return (
            <div className="upper">
                {/*表格填写*/}
                <Table className="upper" columns={columns} bordered dataSource={data} pagination={false}/>
            </div>
        );
    }

}

export default UpperPartOfTheForm;